package sort.simple;

import org.junit.Test;

public class InsertSort {
    @Test
    public void test() {
        int[] a = {5, 2, 7, 4, 1, 3, 8, 9};
        insertionSort(a);
        for (int i = 0; i < a.length; i++) {
            System.out.print(a[i]+" ");
        }
    }

    public void insertionSort(int[] nums) { //升序
        for (int i = 1; i < nums.length; i++) { //认为第0个元素是有序的
            int cur = nums[i];  //记录当前值，防止有序数组向右移动，导致值被覆盖找不到
            int j = i - 1;
            while (j >= 0 && cur < nums[j]) { // 遍历有序序列并将数据挪动到合适位置，将cur放入正确的位置
                nums[j + 1] = nums[j];
                j--;
            }
            nums[j + 1] = cur;
        }
    }
}